//
//  DishList.m
//  myhuibao
//
//  Created by 孙昕 on 14-2-11.
//  Copyright (c) 2014年 myhuibao. All rights reserved.
//

#import "DishListViewContrller.h"
#import "SBJson.h"
#import "DishCell.h"
#import "LoadMoreCell.h"
#import "Config.h"
#import "LoginViewController.h"
#import "OMGToast.h"
#import "UpdateHeaderViewController.h"
#import "RequestLoadingView.h"

@interface DishListViewContrller ()

@end

@implementation DishListViewContrller

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    wqTable=_MainTable;
    delegate=self;
    
    pageIndex=1;
    arr=[[NSMutableArray alloc] initWithCapacity:30];
    
    [self startRequest];
}

- (void)startRequest
{
    if(!loadingView)
    {
        loadingView = [[RequestLoadingView alloc]
                       initRequestLoadingView:self
                       queueFinishSelector:nil
                       viewFrame:LoadingViewFrame];
        
    }
    [self getDish:_merchantId];
    
    [loadingView addRequestToQueue:reqDish];
    
    [loadingView startRequestQueue];
}

- (void) getDish:(int) merchantId
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?merchantID=%d&pageIndex=%d",url_dishList,_merchantId,pageIndex]] ;
    reqDish = [ASIHTTPRequest requestWithURL:url];
    [reqDish setShouldAttemptPersistentConnection:NO];
    [reqDish setDelegate: self];
    [reqDish setDidFinishSelector:@selector(finishDish:)];
    [tableDataArray removeAllObjects];
    
    if (!loadingView.bFirstRequest) {
        
        [reqDish startAsynchronous];
    }
}

- (void)finishDish:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    
    NSDictionary *dic = [jsonStr JSONValue];
    tableDataArray = [dic valueForKey:@"data"];
     returnCount = [tableDataArray count];
    [_MainTable reloadData];
   [Config setExtraCellLineHidden:_MainTable];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)OnBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	int count = [tableDataArray count];
    if (count>=pageSize) {
        return count+1;
    }else
        return count;
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"DishCellIdentifier";
    if([indexPath row] < ([tableDataArray count])) {
        
        DishCell *cell = (DishCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"DishCell" owner:nil options:nil];
            cell = [array objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
        }
        
        NSMutableDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        NSString * imageStr =[NSString stringWithFormat:@"%@%@%@",url_image, [item valueForKey:@"picturePath"],[item valueForKey:@"pictureName"]];
        [item setObject:[NSString stringWithFormat:@"%@%@",[item valueForKey:@"picturePath"],[item valueForKey:@"pictureName"]] forKey:@"image"];
        NSString *imageName =@"";
        if (![imageStr isEqual:[NSNull null] ]) {
            NSArray *array = [imageStr componentsSeparatedByString:@"/"];
            imageName = [array lastObject];
        }
        NSString *imageDataPath = [NSHomeDirectory() stringByAppendingPathComponent:[@"Library/Caches/" stringByAppendingString:imageName]];
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:imageDataPath]];
        if (image) {
            cell.ImageView.image = image;
        }
        else
        {
            cell.ImageView.image = [UIImage imageNamed:@"placeholder.png"];
            //placeholder为在未加载完成加载图片时显示的默认图片
        }
        cell.lbName.text=[item objectForKey:@"name"];
        cell.lbPrice.text=[item objectForKey:@"price"]!=[NSNull null]?[NSString stringWithFormat:@"%@¥",[item objectForKey:@"price"]]:@"无";
        cell.lbCount.text=[NSString stringWithFormat:@"%d",[[item objectForKey:@"recommendTimes"] intValue]];
        cell.lbProvider.text=[item objectForKey:@"provider"]!=[NSNull null]?[item objectForKey:@"provider"]:@"商户";
        cell.tag=indexPath.row;
        [cell.btnRecommand addTarget:self action:@selector(OnRecommand:) forControlEvents:UIControlEventTouchUpInside];
        if([arr indexOfObject:[NSNumber numberWithInt:indexPath.row]]==NSNotFound)
        {
            cell.btnRecommand.enabled=YES;
            [cell.btnRecommand  setBackgroundImage:[UIImage imageNamed:@"zan.jpg"] forState:UIControlStateNormal];
        }
        else
        {
            cell.btnRecommand.enabled=NO;
            [cell.btnRecommand  setBackgroundImage:[UIImage imageNamed:@"img_tuijian_no.jpg"] forState:UIControlStateNormal];
        }
        return cell;
    }else{
        LoadMoreCell *cell = (LoadMoreCell *)[tableView dequeueReusableCellWithIdentifier: @"LoadMoreCellIdentifier"];
        if (cell==nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"LoadMoreCell" owner:nil options:nil];
            cell = [array objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        if(returnCount<pageSize){
            cell.lbText.text=@"";
            cell.hidden = true;
        }else{
            //创建loadMoreCell
            cell.lbText.text=str_more;
        }
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.detailTextLabel.text=@"";
        cell.imageView.image =nil;
        return cell;
        
    }
    
}

-(void)OnRecommand:(UIButton*)button
{
    int memberId = [[Config Instance] getMemberId];
    if(memberId == 0)
    {
        LoginViewController  *view = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
        view.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:view animated:YES];
        return;
    }
    row= [[button superview] superview].tag;
    lbCount=((DishCell*)[[button superview] superview]).lbCount;
    button.enabled=NO;
    [button setBackgroundImage:[UIImage imageNamed:@"img_tuijian_no.jpg"] forState:UIControlStateNormal];
    [arr addObject:[NSNumber numberWithInt:row]];
    NSMutableDictionary *item = [tableDataArray objectAtIndex:row];
    NSString *strUrl=[NSString stringWithFormat:@"%@?memberID=%d&password=%@&productID=%d",url_recommand,[[Config Instance] getMemberId],[[Config Instance] getPassword],[[item objectForKey:@"productID"] intValue]];
    NSURL *url=[NSURL URLWithString:strUrl];
    ASIHTTPRequest *req=[ASIHTTPRequest requestWithURL:url];
    req.delegate=self;
    [req setDidFinishSelector:@selector(RecommandFinish:)];
    [req startAsynchronous];
}

-(void)RecommandFinish:(ASIHTTPRequest*)request
{
    NSString *jsonStr = [request responseString];
    
    NSDictionary *dic = [jsonStr JSONValue];
    [OMGToast showWithText:[dic objectForKey:@"log"] bottomOffset:100];
    if([[dic objectForKey:@"log"] isEqualToString:@"推荐成功"])
    {
        lbCount.text=[NSString stringWithFormat:@"%d",[lbCount.text intValue]+1];
        NSMutableDictionary *item = [tableDataArray objectAtIndex:row];
        int count=[[item objectForKey:@"recommendTimes"] intValue]+1;
        [item removeObjectForKey:@"recommendTimes"];
        [item setObject:[NSNumber numberWithInt:count] forKey:@"recommendTimes"];
    }
}

-(void)cellImageDidLoad:(NSIndexPath *)indexPath image:(UIImage *)image
{
    dispatch_async(dispatch_get_main_queue(), ^{
        DishCell *cell = (DishCell*)[wqTable cellForRowAtIndexPath:indexPath];
        //    cell.imageView.image = image;
        if(image)
            cell.ImageView.image = [image copy];
    });
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.row == [tableDataArray count]) {
        LoadMoreCell *loadMoreCell=(LoadMoreCell *)[tableView cellForRowAtIndexPath:indexPath];
        loadMoreCell.lbText.text=str_loading;
        //        [self performSelectorInBackground:@selector(loadMore) withObject:nil];
        //        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?merchantID=%d&pageIndex=%d",url_dishList,_merchantId,++pageIndex]] ;
        reqDish = [ASIHTTPRequest requestWithURL:url];
        [reqDish setDidFinishSelector:@selector(appendTableWith:)];
        [reqDish setShouldAttemptPersistentConnection:NO];
        reqDish.delegate = self;
        [reqDish startAsynchronous];
        return;
    }    //其他cell的事件
    
}
-(void) appendTableWith:(ASIHTTPRequest *)request
{   //将loadMore中的NSMutableArray添加到原来的数据源listData中.
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    NSMutableArray *data = [dic valueForKey:@"data"];
    returnCount = [data count];
    for (int i=0;i<[data count];i++) {
        [tableDataArray addObject:[data objectAtIndex:i]];
    }
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:pageSize];
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath    *newPath =  [NSIndexPath indexPathForRow:[tableDataArray indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    if ([data count]==0) {
        [_MainTable reloadData];
    }
    //重新调用UITableView的方法, 来生成行.
    [_MainTable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
}

- (IBAction)OnShowUpdate:(id)sender {
    int memberId = [[Config Instance] getMemberId];
    if(memberId == 0)
    {
        LoginViewController  *view = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
        view.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:view animated:YES];
        return;
    }
    UpdateHeaderViewController *view=[[UpdateHeaderViewController alloc] initWithNibName:@"UpdateHeaderViewController" bundle:nil];
    view.hidesBottomBarWhenPushed=YES;
    view.merchantID=_merchantId;
    [self.navigationController pushViewController:view animated:YES];
}
@end
